package sync;

import java.util.concurrent.TimeUnit;

/**
 * @program: thread
 * @description:
 * @author: gongj
 * @Description: TODO
 * @create: 2020-07-12 17:58
 **/
public class syncTest {
    public static void main(String[] args) {
        new Thread(()->{
            syncTest sync = new syncTest();
            sync.methodName3();
        }).start();

        new Thread(()->{
            syncTest sync = new syncTest();
            sync.methodName5();
        }).start();


        new Thread(()->{
            syncTest sync = new syncTest();
            sync.methodName4();
        }).start();
        new Thread(()->{
            syncTest.methodName();
        }).start();
        new Thread(()->{
            syncTest sync = new syncTest();
            sync.methodName6();
        }).start();


    }

    //修饰非静态方法
    public void methodName5() {
        //修饰代码块，this=当前对象（谁调用就指待谁）
        synchronized (this) {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName() + "锁代码块   55555");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public synchronized static void methodName() {
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println(Thread.currentThread().getName()+"锁静态方法   aaa");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //同步非静态方法 ,当前线程的锁便是实例对象methodName
    public synchronized  void methodName3() {
        try {
            TimeUnit.SECONDS.sleep(5);
            System.out.println(Thread.currentThread().getName()+"锁方法并延时   333333");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized  void methodName4() {
            System.out.println(Thread.currentThread().getName()+"锁方法   444444");
    }

    public   void methodName6() {
        System.out.println(Thread.currentThread().getName()+"没有锁   6666");
    }

}
